package com.byq.mm.home.device.adapter;


import com.byq.mm.abstractx.cluster.server.DeviceServer;
import com.byq.mm.abstractx.cluster.server.executor.Executor;
import com.byq.mm.abstractx.device.Cluster;
import com.byq.mm.abstractx.device.Device;
import com.byq.mm.abstractx.engine.CoreEnvironment;
import com.byq.mm.foundation.cluster.server.BasicClusterServer;
import com.tc.gateway.DeviceManagementListener;
import com.tc.gateway.DeviceManager;
import com.tc.gateway.device.AbstractDevice;
import com.tc.gateway.device.GeneralDevice;
import com.tc.gateway.device.remote.ObdIIController;
import com.tc.gateway.device.remote.OnoffController;
import com.tc.gateway.device.remote.OnoffLevelController;
import com.tc.gateway.device.remote.RemoteController;
import com.tc.gateway.device.remote.SimpleSensorController;
import com.tc.gateway.device.type.ObdIIDevice;
import com.tc.gateway.device.type.OnoffDevice;
import com.tc.gateway.device.type.OnoffLevelDevice;
import com.tc.gateway.device.type.SimpleSensorDevice;

public class LocalRemoteBridge implements 
		DeviceManagementListener {
	DeviceManager deviceManager;
	CoreEnvironment coreEnvironment;

	public LocalRemoteBridge(DeviceManager deviceManager,
			CoreEnvironment coreEnvironment) {
		super();
		this.deviceManager = deviceManager;
		this.coreEnvironment = coreEnvironment;
		this.deviceManager.addDeviceListener(this);
	}

	


	@Override
	public void added(GeneralDevice device) {
		RemoteController r = link(device);
		if(r == null)
			return;
		Device d = r.getRemote();
		coreEnvironment.getServerDeviceManager().addDirectChildren(d);
		DeviceServer ds = coreEnvironment.getServerDeviceManager().getDeviceServer(device.getId());
		for (Cluster c : d.getSupportedClusters()){
			BasicClusterServer server = (BasicClusterServer)ds.getClusterServer(c.getId());
			Executor e = r.getExecutor(server);
			coreEnvironment.getExecutorManager().register(d.getId(), c.getId(),
					e);
		}

	}
	RemoteController link(GeneralDevice device){
		if(device instanceof OnoffLevelDevice){
			OnoffLevelDevice od = (OnoffLevelDevice)device;
			OnoffLevelController rst = new OnoffLevelController(od);
			((AbstractDevice)device).addListener(rst);
			return rst;
		}
		if(device instanceof OnoffDevice){
			OnoffDevice od = (OnoffDevice)device;
			OnoffController rst = new OnoffController(od);
			((AbstractDevice)device).addListener(rst);
			return rst;
		}
		
		if(device instanceof SimpleSensorDevice){
			SimpleSensorDevice od = (SimpleSensorDevice)device;
			SimpleSensorController rst = new SimpleSensorController(od);
			((AbstractDevice)device).addListener(rst);
			return rst;
		}
		if(device instanceof ObdIIDevice){
			ObdIIDevice od = (ObdIIDevice)device;
			ObdIIController rst = new ObdIIController(od);
			((AbstractDevice)device).addListener(rst);
			return rst;
		}
		return null;
	}

	
}
